<template>
  <div class="appContainer">
    <es-header title="购物车案例"></es-header>
    <es-goods
      v-for="item in dataList"
      :key="item.id"
      :id="item.id"
      :title="item.goods_name"
      :price="item.goods_price"
      :img="item.goods_img"
      :count="item.goods_count"
      :checked="item.goods_state"
      @boxChange="getBoxState"
      @countChange="getBoxNumber"
    ></es-goods>
    <es-footer @fullChange="getFullState" :amount="amount" :total="total"></es-footer>
  </div>
</template>

<script>
import EsHeader from './components/es-header/EsHeader.vue'
import EsFooter from './components/es-footer/EsFooter.vue'
import EsGoods from './components/es-goods/EsGoods.vue'

export default {
  components: { EsHeader, EsFooter, EsGoods },
  name: 'MyApp',
  data() {
    return {
      dataList: []
    }
  },
  created() {
    this.getDataList()
  },
  methods: {
    // 请求数据
    async getDataList() {
      const { data: res } = await this.$http.get('api/cart')
      if (res.status !== 200) return alert('请求失败')
      this.dataList = res.list
    },
    // 拿到全选按钮选中状态
    getFullState(isFull) {
      this.dataList.forEach(x => {
        x.goods_state = isFull
      })
    },
    // 拿到商品是否被选中状态
    getBoxState(e) {
      const result = this.dataList.find(x => x.id === e.id)
      if (result) {
        result.goods_state = e.value
      }
    },
    // 拿到商品数量
    getBoxNumber(e) {
      const result = this.dataList.find(x => x.id === e.id)
      if (result) {
        result.goods_count = e.value
      }
    }
  },
  computed: {
    // 监听商品总价格
    amount() {
      let a = 0
      this.dataList
        .filter(x => x.goods_state === true)
        .forEach(x => {
          a += x.goods_price * x.goods_count
        })
      return a
    },
    // 监听商品总数量
    total() {
      let t = 0
      this.dataList
        .filter(x => x.goods_state === true)
        .forEach(x => {
          t += x.goods_count
        })
      return t
    }
  }
}
</script>

<style lang="less" scoped>
.appContainer {
  padding-top: 45px;
  padding-bottom: 50px;
}
</style>